<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

use fast\Random;
use Exception;
use think\exception\PDOException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class AppointmentService
{
    // 列表
    public static function index($data)
    {
        $auth = Auth::instance();
        $limit = $data['limit'] ?? 10;
        $full_name = $data['full_name'] ?? '';
        $english_name = $data['english_name'] ?? '';
        $id = $data['id'] ?? '';
        $studio_id = $data['studio_id'] ?? '';
        $channel = $data['channel'] ?? '';
        $level = $data['level'] ?? '';
        $age = $data['age'] ?? '';
        $gender = $data['gender'] ?? '';
        $contact = $data['phone'] ?? $data['contact'] ?? '';
        $start_date = $data['start_date'] ?? '';
        $end_date = $data['end_date'] ?? '';

        $where = [];
        if($full_name) $where['uc.surname|uc.given_name'] = ['like', '%'.$full_name.'%'];
        if($english_name) $where['uc.english_name'] = ['like', '%'.$english_name.'%'];
        if($id) $where['ua.id'] = $id;
        if($studio_id) $where['uc.studio_id'] = ['like', '%'.$studio_id.'%'];
        if($channel) $where['uc.channel'] = $channel;
        if($level) $where['uc.level'] = $level;
        if($age) $where['uc.birthday'] = ['like', '%'.(date('Y')-$age).'%'];
        if($gender) $where['uc.gender'] = $gender;
        if($contact) $where['uc.contact'] = ['like', '%'.$contact.'%'];
        if($start_date) $where['uc.createtime'] = ['>=', strtotime($start_date)];
        if($end_date) $where['uc.createtime'] = ['<=', strtotime($end_date)];

        // 预加载相关数据
        $studio = \app\admin\model\CustomersOrder::alias('uo')
            ->join('__USER_CUSTOMERS__ uc','uc.id = uo.customers_id')
            ->join('__USER_CUSTOMERS_APPOINTMENT__ ua','ua.id = uo.link_id')
            ->where($where)
            ->field('ua.id,uc.surname,uc.given_name,uc.english_name,uc.birthday,uc.gender,uc.primary_phone,ua.createtime,ua.teacher,ua.teacher_role,ua.appointed_by,ua.appointed_on,uo.paid')
            ->order('uc.id', 'desc')
            ->paginate($limit);

        // 收集所有需要查询的用户和用户组ID
        $teacherIds = [];
        $teacherRoleIds = [];
        $appointedByIds = [];

        $studio->each(function($item) use (&$teacherIds, &$teacherRoleIds, &$appointedByIds) {
            $item['full_name'] = $item['given_name'] . ' ' . $item['surname'];
            if ($item['birthday']) {
                $birthYear = substr($item['birthday'], 0, 4);
                $item['birthday'] = $birthYear;
                $item['age'] = (int)date('Y') - $birthYear;
            } else {
                $item['age'] = null;
            }

            if ($item['teacher']) $teacherIds[] = $item['teacher'];
            if ($item['teacher_role']) $teacherRoleIds[] = $item['teacher_role'];
            if ($item['appointed_by']) $appointedByIds[] = $item['appointed_by'];
        });

        // 批量查询
        $teachers = $teacherIds ? \app\admin\model\User::where('id', 'in', array_unique($teacherIds))->column('nickname', 'id') : [];
        $teacherRoles = $teacherRoleIds ? \app\admin\model\UserGroup::where('id', 'in', array_unique($teacherRoleIds))->column('name', 'id') : [];
        $appointedBys = $appointedByIds ? \app\admin\model\User::where('id', 'in', array_unique($appointedByIds))->column('nickname', 'id') : [];

        // 二次遍历赋值
        $studio->each(function($item) use ($teachers, $teacherRoles, $appointedBys) {
            $item['teacher'] = $item['teacher'] ? ($teachers[$item['teacher']] ?? '') : '';
            $item['teacher_role'] = $item['teacher_role'] ? ($teacherRoles[$item['teacher_role']] ?? '') : '';
            $item['appointed_by'] = $item['appointed_by'] ? ($appointedBys[$item['appointed_by']] ?? '') : '';
            return $item;
        });

        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$studio];
    }

    // 添加
    public static function add($data)
    {
        $auth = Auth::instance();
        // 验证规则
        $validate = new Validate([
            'customers_id' => 'require',
            'type' => 'require',
            'date_time' => 'require',
            'teacher_role' => 'require',
            'teacher' => 'require',
            'number' => 'require|number',
            'validtime' => 'require',
            'appointed_by' => 'require',
            'appointed_on' => 'require',
            'currency' => 'require',
            'amount' => 'require|float',
            'refundable' => 'require',
            'cool_coin' => 'require',
            'description' => 'require',
        ], [
            'customers_id.require' => 'CustomersID is not empty',
            'type.require' => 'Appointment Type is not empty',
            'date_time.require' => 'Appointment Date is not empty',
            'teacher_role.require' => 'Appointment Teacher Role is not empty',
            'teacher.require' => 'Appointment Teacher is not empty',
            'number.require' => 'Number of Lessons or Event is not empty',
            'number.number' => 'Number of Lessons must be numeric',
            'validtime.require' => 'Validtime is not empty',
            'appointed_by.require' => 'Appointed By is not empty',
            'appointed_on.require' => 'Appointed On is not empty',
            'currency.require' => 'Currency is not empty',
            'amount.require' => 'Amount not empty',
            'amount.float' => 'Amount must be numeric',
            'refundable.require' => 'Refundable is not empty',
            'cool_coin.require' => 'Cool Coin is not empty',
            'description.require' => 'Description is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {
            Db::startTrans(); // 开始事务

            // 创建预约记录
            $appointment = \app\admin\model\CustomersAppointment::create([
                'customers_id' => htmlspecialchars($data['customers_id'], ENT_QUOTES),
                'type' => htmlspecialchars($data['type'], ENT_QUOTES),
                'date_time' => htmlspecialchars($data['date_time'], ENT_QUOTES),
                'teacher_role' => htmlspecialchars($data['teacher_role'], ENT_QUOTES),
                'teacher' => htmlspecialchars($data['teacher'], ENT_QUOTES),
                'number' => floatval($data['number']),
                'validtime' => htmlspecialchars($data['validtime'], ENT_QUOTES),
                'appointed_by' => htmlspecialchars($data['appointed_by'], ENT_QUOTES),
                'appointed_on' => htmlspecialchars($data['appointed_on'], ENT_QUOTES),
            ]);

            // 创建订单记录
            $result = \app\admin\model\CustomersOrder::create([
                'customers_id' => htmlspecialchars($data['customers_id'], ENT_QUOTES),
                'type' => htmlspecialchars($data['type'], ENT_QUOTES),
                'link_id' => $appointment->id,
                'order_no' => getNewOrderNo(16),
                'currency' => htmlspecialchars($data['currency'], ENT_QUOTES),
                'amount' => floatval($data['amount']),
                'item' => json_encode([
                    'refundable' => htmlspecialchars($data['refundable'], ENT_QUOTES),
                    'cool_coin' => htmlspecialchars($data['cool_coin'], ENT_QUOTES),
                    'description' => htmlspecialchars($data['description'], ENT_QUOTES),
                ])
            ]);

            if ($result) {
                Db::commit();
                $item = json_decode($result->item, true);
                $result['refundable'] = $item['refundable'];
                $result['cool_coin'] = $item['cool_coin'];
                $result['description'] = $item['description'];
                unset($result['item']);
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            } else {
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        } catch (\Exception $e) {
            Db::rollback();
            // 使用通用错误消息而不是暴露具体数据库错误
    //        return $e->getMessage();
            return ['code' => 400, 'msg' => 'Database operation failed', 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 编辑
    public static function edit($data)
    {
        // 设置默认值
        $data['mobile'] = $data['phone'] ?? '';
        $fields = [
            'primary_relationship', 'primary_name', 'primary_phone', 'primary_email', 'primary_account',
            'secondary_relationship', 'secondary_name', 'secondary_phone', 'secondary_email', 'secondary_account'
        ];

        foreach ($fields as $field) {
            $data[$field] = $data[$field] ?? '';
        }

        // 参数验证
        if (empty($data['id']) || !is_numeric($data['id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        $customers_id = \app\admin\model\CustomersAppointment::where('id', $data['id'])->value('customers_id');
        if (!$customers_id) {
            return ['code'=>400, 'msg'=>'Information does not exist', 'state'=>'NOT_FOUND', 'data'=>null];
        }
        $data['id'] = $customers_id;

        unset($data['phone']);

        // 权限验证
        $auth = Auth::instance();
        if (!$auth->check()) {
            return ['code'=>403, 'msg'=>'Permission denied', 'state'=>'PERMISSION_DENIED', 'data'=>null];
        }

        // 验证规则
        $validate = new Validate([
            'studio_id' => 'require',
            'surname' => 'require',
            'given_name' => 'require',
            'english_name' => 'require',
            'status'    =>  'require',
            'gender' => 'require',
            'birthday' => 'require',
            'mobile' => 'require',
            'channel' => 'require',
            'school' => 'require',
            'school_grade' => 'require',
            'description' => 'require',
            'avatar' => 'require',
            'primary_relationship' => 'require',
            'primary_name' => 'require',
            'primary_phone' => 'require',
            'primary_account' => 'require',
        ], [
            'studio_id.require' => 'StudioID is not empty',
            'surname.require' => 'Surname is not empty',
            'given_name.require' => 'Given name is not empty',
            'english_name.require' => 'English name is not empty',
            'status.require' => 'Status is not empty',
            'gender.require' => 'Gender is not empty',
            'birthday.require' => 'Birthday is not empty',
            'mobile.require' => 'Mobile is not empty',
            'channel.require' => 'Channel is not empty',
            'school.require' => 'School is not empty',
            'school_grade.require' => 'School Grade is not empty',
            'description.require' => 'Description not empty',
            'avatar.require' => 'Avatar is not empty',
            'primary_relationship.require' => 'Primary Relationship is not empty',
            'primary_name.require' => 'Primary Name is not empty',
            'primary_phone.require' => 'Primary Phone is already exists',
            'primary_account.require' => 'Primary Social Acount is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        Db::startTrans();
        try {
            $result = \app\admin\model\UserCustomers::update($data);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            // 生产环境应使用更通用的错误信息
            return ['code' => 400, 'msg' => 'Database operation failed', 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 删除
    public static function del($data)
    {
        $auth = Auth::instance();
        // 更严格的参数验证
        if (empty($data['id']) || !ctype_digit((string)$data['id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 查询学习馆数据
        $details = \app\admin\model\CustomersAppointment::find($data['id']);
        if (!$details) {
            return ['code'=>400, 'msg'=>'Customer does not exist', 'state'=>'NOT_FOUND', 'data'=>null];
        }

        // 启用事务删除数据
        Db::startTrans();
        try {
            $result = \app\admin\model\CustomersAppointment::destroy($data['id']);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database operation failed', 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 支付
    public static function payment($data)
    {
        $data['paidtime'] = $data['payment_date'];
        $data['payment_by'] = $data['payment_collected_by'];
        unset($data['payment_date']);
        unset($data['payment_collected_by']);
        $auth = Auth::instance();

        // 验证规则
        $validate = new Validate([
            'id' => 'require',
            'paidtime' => 'require|date',
            'payment_by' => 'require|number',
        ], [
            'id.require' => 'Order ID is required',
            'paid.require' => 'Paid amount is required',
            'paidtime.require' => 'Payment date is required',
            'paidtime.date' => 'Invalid payment date format',
            'payment_by.require' => 'Payment collector is required',
            'payment_by.number' => 'Invalid payment collector ID',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        Db::startTrans();
        try {
            $data['method'] = 'cash';
            $result = \app\admin\model\CustomersOrder::update($data);

            if($result){
                Db::commit();

                // 查询订单及关联用户信息
                $order = \app\admin\model\CustomersOrder::where('id', $data['id'])->find();
                $user = \app\admin\model\User::where('id', $data['payment_by'])->field('id,english_name')->find();

                if ($order && $user) {
                    $order['nickname'] = $user['english_name'];
                } else {
                    $order['nickname'] = '';
                }

                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$order];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\PDOException $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database operation failed', 'state' => 'DATABASE_ERROR', 'data' => null];
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'System error', 'state' => 'SYSTEM_ERROR', 'data' => null];
        }
    }

    // 记录
    public static function record($data)
    {
        try {
            $auth = Auth::instance();
            $limit = $data['limit'] ?? 10;

            // 验证参数
            $validate = new Validate([
                'customers_id' => 'require',
            ], [
                'customers_id.require' => 'CustomersID is not empty',
            ]);

            if (!$validate->check($data)) {
                return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
            }

            // 使用join查询避免N+1问题
            $list = \app\admin\model\CustomersOrder::alias('co')
                ->join('__USER_CUSTOMERS__ uc', 'uc.id = co.customers_id')
                ->join('__USER_CUSTOMERS_APPOINTMENT__ uca', 'uca.id = co.link_id')
                ->where('co.customers_id', $data['customers_id'])
                ->where('co.type', 'appointment') // 保留原始条件，但检查是否需要
                ->field('co.*,uca.teacher,uc.english_name as customers_name,uc.avatar as customers_avatar')
                ->paginate($limit);

            return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$list];

        } catch (\Exception $e) {
            return ['code'=>500, 'msg'=>'Server Error', 'state'=>'INTERNAL_ERROR', 'data'=>null];
        }
    }


    // 详情
    public static function view($data)
    {
        try {
            $auth = Auth::instance();
            if (empty($data['id']) || !is_numeric($data['id'])) {
                return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
            }

            $customers_id = \app\admin\model\CustomersAppointment::where('id', intval($data['id']))->value('customers_id');
            if (!$customers_id) {
                return ['code'=>400, 'msg'=>'Information does not exist', 'state'=>'NOT_FOUND', 'data'=>null];
            }

            $result = \app\admin\model\UserCustomers::where(['id' => intval($customers_id)])
                ->field('avatar,studio_id,surname,given_name,status,birthday,gender,mobile,channel,school,school_grade,description,primary_relationship,primary_name,primary_phone,primary_email,primary_account,secondary_relationship,secondary_name,secondary_phone,secondary_email,secondary_account,collected_id,createtime,assign_to,assign_by,assigntime')
                ->find();

            if($result){
                $birthDate = new \DateTime($result['birthday']);
                $currentDate = new \DateTime();
                $result['age'] = $birthDate->diff($currentDate)->y;
                $result['avatar'] = $result['avatar'] ?? '/assets/img/avatar.png';

                // 处理收集者信息
                if ($result['collected_id']) {
                    $collected = \app\admin\model\User::where('id', intval($result['collected_id']))
                        ->field('id,surname,given_name,group_id')
                        ->find();
                    if ($collected) {
                        $result['collected_by'] = $collected['given_name'] . $collected['surname'];
                        $result['collected_role'] = \app\admin\model\UserGroup::where('id', intval($collected['group_id'] ?? 0))->value('name');
                    }
                }
                $result['collected_date'] = date('Y-m-d H:i:s', $result['createtime']);

                // 处理分配者信息
                if ($result['assign_by']) {
                    $assign = \app\admin\model\User::where('id', intval($result['assign_by']))
                        ->field('id,surname,given_name,group_id')
                        ->find();
                    if ($assign) {
                        $result['assigned_by'] = $assign['given_name'] . $assign['surname'];
                        $result['assigned_role'] = \app\admin\model\UserGroup::where('id', intval($assign['group_id'] ?? 0))->value('name');
                    }
                }
                $result['assigned_date'] = date('Y-m-d H:i:s', $result['assigntime']);
            }

            return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
        } catch (\Exception $e) {
    //        return $e->getMessage();
            return ['code'=>500, 'msg'=>'Server error', 'state'=>'INTERNAL_ERROR', 'data'=>null];
        }
    }

    // 新增跟进
    public static function add_follow_up($data)
    {
        $auth = Auth::instance();
        // 验证规则
        $validate = new Validate([
            'customers_id' => 'require',
            'english_name' => 'require',
            'gender' => 'require|in:male,female,other',
            'age' => 'require|number|between:1,120',
            'follow_up_type' => 'require',
            'follow_up_by' => 'require',
            'follow_up_content' => 'require',
        ], [
            'customers_id.require' => 'Customers is not empty',
            'english_name.require' => 'English Name is not empty',
            'gender.require' => 'Gender is not empty',
            'gender.in' => 'Gender is invalid',
            'age.require' => 'Age is not empty',
            'age.number' => 'Age must be a number',
            'age.between' => 'Age must between 1 and 120',
            'follow_up_type.require' => 'Follow Up Type is not empty',
            'follow_up_by.require' => 'Follow Up By is not empty',
            'follow_up_content.require' => 'Follow Up Content is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        Db::startTrans();
        try {
            $result = \app\admin\model\UserFollowUp::create($data);

            if ($result) {
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            } else {
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database operation failed', 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }


    // 跟进记录
    public static function list_follow_up($data)
    {
        $auth = Auth::instance();

        // 提前验证必要参数
        if (empty($data['customers_id']) || !is_numeric($data['customers_id'])) {
            return ['code'=>400, 'msg'=>'Invalid customers_id', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        $limit = isset($data['limit']) && is_numeric($data['limit']) ? intval($data['limit']) : 10;
        $where = ['customers_id' => intval($data['customers_id'])];

        $defaultAvatar = cdnurl('/assets/img/avatar.png', true);

        if(isset($data['follow_up_type']) && $data['follow_up_type']) {
            $where['follow_up_type'] = ['like', "%{$data['follow_up_type']}%"];
        }

        if(isset($data['follow_up_by']) && $data['follow_up_by']) {
            $where['follow_up_by'] = ['like', "%{$data['follow_up_by']}%"];
        }

        if(isset($data['start_time']) && isset($data['end_time']) && $data['start_time'] && $data['end_time']){
            $start_time = strtotime($data['start_time']);
            $end_time = strtotime($data['end_time']);

            if ($start_time === false || $end_time === false) {
                return ['code'=>400, 'msg'=>'Invalid time format, expected Y-m-d H:i:s', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
            }

            if ($start_time > $end_time) {
                return ['code'=>400, 'msg'=>'Start time must be before end time', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
            }

            $where['createtime'] = ['between', [$start_time, $end_time]];
        }

        $list = \app\admin\model\UserFollowUp::where($where)->paginate($limit)->each(function ($item, $key) use ($defaultAvatar) {
            $avatar = \app\admin\model\UserCustomers::where('id', $item['customers_id'])->value('avatar');
            $item['avatar'] = $avatar ? cdnurl($avatar, true) : $defaultAvatar;
            $item['follow_up_time'] = date('Y-m-d H:i:s', $item['createtime']);
        });

        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$list];
    }


    // 跟进export
    public static function follow_up_export($data)
{
    if (empty($data['id']) || !is_numeric($data['id'])) {
        return ['code' => 400, 'msg' => 'Invalid parameters', 'state' => 'INVALID_ARGUMENT', 'data' => null];
    }

    try {
        $follow_up = \app\admin\model\UserFollowUp::alias('f')
            ->where('f.id', $data['id'])
            ->find();
        if (!$follow_up) {
            return ['code' => 400, 'msg' => 'Data does not exist', 'state' => 'NOT_FOUND', 'data' => null];
        }

        $customers = \app\admin\model\UserCustomers::alias('c')
            ->where('c.id', $follow_up['customers_id'])
            ->find();
        if (!$customers) {
            return ['code' => 400, 'msg' => 'Customers does not exist', 'state' => 'NOT_FOUND', 'data' => null];
        }

        // 计算准确年龄
        $birthYear = substr($customers['birthday'], 0, 4);
        $birthMonthDay = substr($customers['birthday'], 5);
        $currentYear = date('Y');
        $age = (int)$currentYear - (int)$birthYear;
        if (date('m-d') < $birthMonthDay) {
            $age--;
        }

        $info = [
            'avatar' => cdnurl($customers['avatar'], true),
            'full_name' => $customers['surname'] . $customers['given_name'],
            'english_name' => $customers['english_name'],
            'gender' => $customers['gender'],
            'age' => $age,
            'studio_id' => $customers['studio_id'],
            'status' => $customers['status'],
            'date_of_birth' => $customers['birthday'],
            'phone' => $customers['mobile'],
            'channel' => $customers['channel'],
            'school' => $customers['school'],
            'school_grade' => $customers['school_grade'],
            'description' => $customers['description'],
            'primary_relationship' => $customers['primary_relationship'],
            'primary_name' => $customers['primary_name'],
            'primary_phone' => $customers['primary_phone'],
            'primary_email' => $customers['primary_email'],
            'primary_account' => $customers['primary_account'],
            'secondary_relationship' => $customers['secondary_relationship'],
            'secondary_name' => $customers['secondary_name'],
            'secondary_phone' => $customers['secondary_phone'],
            'secondary_email' => $customers['secondary_email'],
            'secondary_account' => $customers['secondary_account'],
        ];

        // 获取用户相关信息
        $userIds = array_filter([
            $customers['collected_id'],
            $customers['assign_to'],
            $customers['assign_by'],
            $customers['create_by']
        ]);
        $users = [];
        if (!empty($userIds)) {
            $users = \app\admin\model\User::whereIn('user.id', $userIds)
                ->with(['group' => function($query) {
                    $query->field('id,name');
                }])
                ->column('nickname,group_id', 'user.id');
        }

        // 处理收集者信息
        $collected = $users[$customers['collected_id']] ?? null;
        $info['collected_by'] = $collected['nickname'] ?? '';
        $info['role'] = $collected['group']['name'] ?? '';
        $info['collected_date'] = $customers['collectedtime'] ? date('Y-m-d H:i:s', $customers['collectedtime']) : '';

        // 处理分配信息
        $assignTo = $users[$customers['assign_to']] ?? null;
        $info['assign_to'] = $assignTo['nickname'] ?? '';
        $info['assign_role'] = $assignTo['group']['name'] ?? '';
        $info['assign_by'] = $users[$customers['assign_by']]['nickname'] ?? '';
        $info['assign_date'] = $customers['assigntime'] ? date('Y-m-d H:i:s', $customers['assigntime']) : '';

        // 处理创建者信息
        $createBy = $users[$customers['create_by']] ?? null;
        $info['create_by'] = $createBy['nickname'] ?? '';
        $info['created_role'] = $createBy['group']['name'] ?? '';
        $info['created_date'] = $customers['createtime'] ? date('Y-m-d H:i:s', $customers['createtime']) : '';

        // 跟进信息
        $info['follow_up_time'] = $follow_up['createtime'] ? date('Y-m-d H:i:s', $follow_up['createtime']) : '';
        $info['follow_up_content'] = $follow_up['follow_up_content'] ?? '';
        $info['follow_up_by'] = \app\admin\model\User::alias('u')
            ->where('u.id', $follow_up['follow_up_by'])
            ->value('nickname') ?? '';
        $info['image'] = $follow_up['image'] ? cdnurl($follow_up['image'], true) : '';

        return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $info];
    } catch (\Exception $e) {
        return $e->getMessage();
        return ['code' => 500, 'msg' => 'Server error', 'state' => 'INTERNAL_ERROR', 'data' => null];
    }
}


}
